package com.pencilisland.pay.app.mp.service.impl;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.bean.constant.GoodsConstant;
import com.pencilisland.pay.api.bean.mp.app.MessageRequest;
import com.pencilisland.pay.api.bean.mp.app.MessageResponse;
import com.pencilisland.pay.api.bean.mp.app.WxPayUnifyOrderREQ;
import com.pencilisland.pay.api.bean.mp.app.WxPayUnifyOrderRES;
import com.pencilisland.pay.api.bean.wxpay.WxLoginResp;
import com.pencilisland.pay.api.config.AppConfig;
import com.pencilisland.pay.api.entity.GoodsEntity;
import com.pencilisland.pay.api.service.CacheService;
import com.pencilisland.pay.app.mp.service.MBService;

/**
 * 报文逻辑处理.微信支付统一下单
 *
 * @author breeze
 */
@Service("MB_wxPayUnifyOrder")
public class WxPayUnifyOrderMB implements MBService {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	AppConfig config;

	@Autowired
	CacheService cacheService;

	@Autowired
	RestTemplate rest;
	@Autowired
	ObjectMapper objectMapper;

	@Override
	public MessageResponse process(MessageRequest request) {
		WxPayUnifyOrderREQ requestBean = getRequestBody(request);
		log.info("【{}】购买商品【{}】【{}】", request.getIp(), requestBean.getGoodsCode(), requestBean.getBuyNum());
		// 购买校验
		GoodsEntity goodsE = cacheService.retrieveGoods(requestBean.getGoodsCode());
		if (goodsE == null) {
			return new WxPayUnifyOrderRES(false, null, "购买商品不存在");
		}
		
		if(goodsE.getStatus()==GoodsConstant.STATUS_0){
			return new WxPayUnifyOrderRES(false, null, "购买商品未开通购买");
		}

		if (goodsE.getStock() < requestBean.getBuyNum()) {
			return new WxPayUnifyOrderRES(false, null, "购买商品库存不够");
		}
		
		WxLoginResp result = (WxLoginResp) cacheService.get(request.getSessionId());
		if(result==null||StringUtils.isEmpty(result.getOpenId())){
			return new WxPayUnifyOrderRES(false, null, "没有登录数据");
		}
		requestBean.setOpenId(result.getOpenId());
		requestBean.setOrderIp(request.getIp());

		HttpHeaders headers = new HttpHeaders();
		headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON_UTF8));
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);

		String url = config.getCoreServer() + "/core/app/wxpay/unifyorder";

		HttpEntity<WxPayUnifyOrderREQ> httpRequest = new HttpEntity<>(requestBean, headers);

		return rest.postForObject(url, httpRequest, WxPayUnifyOrderRES.class);
	}

	public WxPayUnifyOrderREQ getRequestBody(MessageRequest request) {
		return objectMapper.convertValue(request.getBody(), WxPayUnifyOrderREQ.class);
	}

}
